import getuserTempId from "@/utils";
import { getToken,setToken,removeToken } from "@/utils/token";
import { SET_USERTOKEN_STATE,SET_USERINFO_STATE,
	RESET_USER_STATE,
 } from "../constant-type";
 import { reqLogin, reqUserInfo , reqLogout} from "@/api";

const state = {
	userTempId: getuserTempId(),
	token:getToken()||'',
	userInfo:{}
};

const mutations = {
	// 1.修改vue中token的值
	[SET_USERTOKEN_STATE](state,payload){
		state.token=payload.token
		// 使token持久化
		setToken(payload.token)
	},
	// 2.设置vuex中userInfo的值
	[SET_USERINFO_STATE](state,payload){
		state.userInfo=payload.userInfo
		
	},
	//3.退出时，清空token和user数据
	[RESET_USER_STATE](state){
state.token=''//清除token
removeToken()//清除持久化的token
state.userInfo={}//清除用户信息
	}
};
const actions = {
	// 1.登录请求获取token
	async reqLogin({commit},userInfo){
		try {
		const re=await reqLogin(userInfo)
	
		commit(SET_USERTOKEN_STATE,re)
	
		} catch (e) {
			alert(e.message)
			return Promise.reject();
		}
	},
// 2.请求用户信息
async getUserInfo({commit}){
	try {
		const re=await reqUserInfo()
		commit(SET_USERINFO_STATE,{userInfo:re})
	} catch (e) {
		alert(e.message)
		return Promise.reject(e)
	}
},
//3.退出登录
async getLogout({commit}){
	try {
		await reqLogout()
		alert('退出登录成功')
		commit(RESET_USER_STATE)
	} catch (e) {
		alert(e.message)
	}
},
  //4. 清理user数据的action方法
  resetToken({ commit }) {
    commit(RESET_USER_STATE);
  },

};
export default {
	namespaced: true,//开启独立命名空间
	state,

	mutations,
	actions,
};

